<template>




	<div class="merak-container-has-aside" curPageName="7dsfds53123">


		<div class="merak-aside">
			<treeNode @node-change="nodeChange" :defTreeValue="org_id"></treeNode>
		</div>
		<div class="merak-card merak-container-has-search" v-waterMarker>
			<div>
				<searchBar :close-plan="true" ref="searchbar" :placeholder='$t("manage_record.placeholder")'
					:search_val=search_val @search-event="searchBarPost" v-model="searchform">


					<!-- 高级搜索弹出框 插槽-->
					<template #searchForm="searchProp">

						<!--  高级搜索弹出框内容-->
						<div class="modal-content">
							<!-- 高级搜索 -->
							<div class="modal-title">

							</div>

							<div class="modal—body">
								<el-scrollbar class="search_from_scrollbar" height="100%">
									<div class="scrollbar-content">
										<!-- 已选参数 组件-->
										<selectedParams
											class=""
											v-model="searchform"
											label="label"
											val="value"
											option-key="options"
										></selectedParams>

										
										<!-- 表单 -->
										<el-form :model="searchform" :rules="searchformRules" label-position="top"
											ref="searchFormRef">

											<el-row :gutter="40">
												<el-col :span="lang=='ru'?8:6">
													<el-form-item :label='$t("manage_record.employee_name")'
														prop="employee_name.value">
														<el-input class="qf_input"
															v-model="searchform.employee_name.value" />
													</el-form-item>
												</el-col>
												<el-col :span="lang=='ru'?8:6">
													<el-form-item prop="job_number.value" :label='$t("manage_record.job_number")'>
														<el-input class="qf_input"
															v-model="searchform.job_number.value" />
													</el-form-item>
												</el-col>
												<el-col :span="lang=='ru'?8:6">
													<el-form-item prop="rangeTime.value" :label='$t("manage_record.rangetime")'>

														<el-date-picker v-model="rangeTime" type="daterange"
															:start-placeholder='$t("leaves_record_list.begin")'
															:end-placeholder='$t("leaves_record_list.end")'
															class="qf_date" @change="dataPost" :format="format"
															value-format="YYYY-MM-DD" />
													</el-form-item>
												</el-col>
												<el-col :span="lang=='ru'?8:6">
													<el-form-item  prop="type.value" :label='$t("manage_record.type")'>
														<el-select class="qf_select" v-model="searchform.type.value"
															:placeholder='$t("merak.placeholder_select")'>
															<el-option v-for="item in searchform.type.options"
																:key="item.value" :label="item.label"
																:value="item.value" />
														</el-select>
													</el-form-item>
												</el-col>
											</el-row>

										</el-form>
										<!-- 表单 -->
									</div>
								</el-scrollbar>
							</div>
							<div class="modal-footer">
								<!-- 取消 -->
								<el-button type="default" @click="closeModal(searchFormRef)">{{ $t("merak.reset")
									}}</el-button>
								<!-- 搜索 -->
								<el-button type="primary" @click="submitForm(searchFormRef)">{{ $t("merak.search")
									}}</el-button>
								<!-- 保存搜索方案 -->
								<el-button plain type="primary" v-if="searchProp.closePlan" @click="showPlanModal">
									{{ $t("merak.save_search_scheme") }}
								</el-button>
							</div>
						</div>
						<!--  高级搜索弹出框内容-->
					</template>
					<!-- /高级搜索弹出框 插槽-->
					<!-- <template #header> 
						<div>
							
							<el-date-picker
							v-model="rangeTime"
							type="daterange"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
					
				            @change="dataPost"
							:format="format"
							value-format="YYYY-MM-DD"
						/>
						</div>
							
					</template> -->
				</searchBar>
			</div>
			<div class="merak-table-wrapper">
				<MerakXTable ref="tableRef" :columns-by-store="JSON.parse(JSON.stringify(state.columns))"
					:query-columns="handleQueryColumns" :query-data="handleQueryData" :params="state.params"
					:column-min-width="120" :column-type="columnTypeArr" :batch-click="handleBatchClick">



					<template #sp_type_slots="{ row }">
						<span :style="`color:${row.color}`">
							<i class="dian" :style="`background:${row.color}`"></i>{{ row.sp_type}}
						</span>


					</template>

					<template #handler="{ row }">
						<div>
							<el-button type="primary" link @click="showRemaining(row)">
								{{$t("manage_record.see")}}</el-button>
						</div>
					</template>



				</MerakXTable>
			</div>
		</div>
		<!-- 查看详情start -->



		<div >
			<el-drawer  modal-class="merak_modal xq" v-model="showRemainingModal" direction="rtl"
				size="30%">
				<template #header>
					<div class="merak_modal_title">{{userName}}{{$t("manage_record.isdetail")}}</div>
				</template>
				<div v-loading="xqloading">

					<el-form label-width="40%">
	

						<el-form-item :label="label" :span="8" v-for="(value_text,label) in xqfrom">
							{{value_text}}
						</el-form-item>
	

					</el-form> 
				</div>


			</el-drawer>
	  </div>
		<!-- 查看详情end -->
	</div>






</template>

<script lang="ts" setup name="manageRecord">
	import useDateFormat from "@/hooks/useDateFormat";


	import { Plus, Edit, Delete, EditPen } from '@element-plus/icons-vue';

	import { ref, reactive, onMounted, getCurrentInstance } from "vue";


	import searchBar from "@/components/SearchBar";
	import merakColapse from "@/components/merakColapse/index.vue";
	import selectedParams from "@/components/SearchBar/components/selectedParams.vue";


	import MerakXTable, { MerakXTableInstance, MerakXTableColumn, MerakXTableQuery } from "@/components/MerakXTable";
	import { moreConfirm, confirmWarningMsg, successMsg, warnMsg, failMsg, confirmSuccessMsg, delConfimMsg } from "@/utils/messageUtils";
	import { getRecordHeadApi, getRecordListApi, getxqApi } from "@/api/modules/personalManagementApi/holiday";
	import treeNode from '@/views/personalManagement/a-components/oragnizationTree/index.vue';
	import { getLocationParams } from "@/utils/index";

	import type { ElForm } from "element-plus";
	import I18n from "@/languages/index";
import { watch } from "vue";


	const $t = I18n.global.t;
	const columnTypeArr = reactive([]);
	const lang=ref("");
	lang.value=$t("lang");
	if ($t("lang") == 'ru') {
		Object.assign(columnTypeArr, [{ type: 'handle', width: 110, slot: 'handler' }]);
	} else {
		Object.assign(columnTypeArr, [{ type: 'handle', width: 80, slot: 'handler' }]);
	}


	const { format } = useDateFormat();
	type FormInstance = InstanceType<typeof ElForm>;
	const leavesRef = ref < FormInstance > ();

	const { proxy } = getCurrentInstance();


	const tableRef = ref < MerakXTableInstance > ();

	const org_id = ref("")
	const userName = ref("")

	const formattedDate = () => {//转换相应格式的日期
		const today = new Date();
		let year = today.getFullYear();
		let month = (today.getMonth() + 1).toString().padStart(2, '0');
		let day = today.getDate().toString().padStart(2, '0');
		return `${year}-${month}-${day}`;
	}
	const formattedDate2 = () => {//转换相应格式的日期
		const today = new Date();
		let year = today.getFullYear();
		let month = (today.getMonth() + 1).toString().padStart(2, '0');
		let day = today.getDate().toString().padStart(2, '0');
		return `${year}-${month}-01`;
	}

	const endtime = formattedDate();
	const starttime = formattedDate2();


	const rangeTime = ref([]);





	//接收url参数
	const newUrl = new URL(window.location.href);
	let url_org_id = getLocationParams(newUrl.href, 'org_id');
	org_id.value = url_org_id;

	//批量操作
	const handleBatchClick = async (e) => {


	}


	//#region 搜索表单
	const search_val = ref("");
	const searchFn = (e) => {
		console.log(e)
		// e.searchVal
		state.params.key_words = e.search;
	}


	const nodeChange = (data: any) => {
		// console.log(data)
		// 构建新的URL
		const newUrl = new URL(window.location.href);
		//console.log(newUrl)
		newUrl.searchParams.set('org_id', data.org_id);
		org_id.value = data.org_id;
		// 使用pushState更新浏览器历史记录
		window.history.pushState({}, '', newUrl.toString());

		search_val.value = "";

		// console.log(search_val.value)
		tableRef.value?.reloadData();
	}






	//权限数据
	let authArr = ref({});

	//列表内容展示区
	const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => {
		const params: Record<string, any> = {};
		if (!!page) {
			// console.log(params)
			if (org_id.value == false) {

				org_id.value = ''
			}
			// console.log(org_id.value)
			// console.log(from)



			Object.assign(params, { ...page, org_id: org_id.value, search: params.search, begin_date: rangeTime.value[0], end_date: rangeTime.value[1] });


		}
		// console.log(from)
		for (let key of Object.keys(from)) {
			if (!!from[key]) {
				params[key] = from[key]
			}
		}
		return await getRecordListApi(params).then(res => {
			// console.log(res)
			if (res.code == ResultEnum.SUCCESS) {
				let data = res.data;

				Object.assign(authArr, data.auth_list)


				// 权限02
				authArr.value = res.auth_list;












				// console.log(searchform.type.options)
				searchform.type.options = data.type;

				const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };

				return table_data;
			}
		})

	};

	const showRemainingModal = ref(false)
	const showRemainingData = ref([]);
	const xqfrom = ref();
	const xqloading = ref(false);



	//打开查看请假详情
	const showRemaining = (row) => {
		xqloading.value = true;
		showRemainingModal.value = true;
		// console.log(row)
		userName.value = row.employee_name;
		getxqApi({ id: row.id }).then(res => {
			xqloading.value = false;
			if (res.code == ResultEnum.SUCCESS) {
				xqfrom.value = res.data;
				// showRemainingData.value = list;

			}
		})
	}




	//表头信息
	const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
		return await getRecordHeadApi().then(res => {
			if (res.code == ResultEnum.SUCCESS) {




				let data = res.data as MerakXTableQuery.Columns;
				// const { pageSize, columns } = data as { pageSize: number; columns: MerakXTableColumn[] };


				// console.log(data)
				for (let index = 0; index < data.columns.length; index++) {
					const element = data.columns[index];
					// console.log(element)
					if (element.field == "sp_type") {
						element["slots"] = { default: "sp_type_slots" }
					}


				}
				// console.log(data)



				//slots: { default: "funBtn", }


				//获取表头后使用tableid 获取搜索方案
				queryFilterOptions(data);

				state.columns = data.columns;
				return data;
			}
		})
	};













	// 获取高级搜索方案
	const queryFilterOptions = async data => {
		searchbar.value.getPlanList(data.table_id);
		// 初始化接口需要传入队列 loading 暴露的 id
	};








	const state = reactive < {
		params: Record < string, any>;
	columns: MerakXTableColumn[];
}> ({
		params: {
			key_words: ""
		},
		columns: []
	});

















	const dataPost = params => {
		// console.log(params)

		searchform.rangeTime.value = rangeTime.value[0] + ' ~ '+ rangeTime.value[1] ;


		// let postParams = { ...params.params, search: state.params.search, begin_date: rangeTime.value[0], end_date: rangeTime.value[1] };
		// state.params = postParams;
	};
















	// 高级搜索
	// 高级搜索表单
	const searchFormRef = ref < FormInstance > ();
	const searchform = reactive({

		employee_name: {
			label: "姓名",
			value: ""
		},
		job_number: {
			label: "工号",
			value: ""
		},
		rangeTime: {
			label: "时间",
			value: ''
		},
		type: {
			label: "请假类型",
			value: "",
			text: "rewiqruhewqio",
			type: "select",
			options: []
		}



	});


watch(searchform.rangeTime, val => {
	console.log(searchform.value)
	if(!searchform.rangeTime.value){

		rangeTime.value=[];

	}
	

 
});



	// 高级搜索表单验证
	const searchformRules = reactive({
		employee_name:[],
		job_number:[],
		rangeTime:[],
		type:[]
	});

	//高级搜索模态
	const searchbar = ref();


	//触发了快速搜索或者搜索方案
	const searchBarPost = params => {
		// console.log(params)
		searchform.employee_name.value = "";
		searchform.job_number.value = "";
		rangeTime.value = [];
		searchform.type.value = "";

		let postParams = { ...params.params, search: params.search };
		state.params = postParams;
	};

	//点击取消按钮关闭高级搜索模态框
	const closeModal = (formEl: FormInstance | undefined) => {
		searchFormRef.value?.resetFields();
		searchbar.value.modalHide();
		searchbar.value.clear();


		searchform.employee_name.value = "";
		searchform.job_number.value = '';
		rangeTime.value = ['', ''];
		searchform.type.value = '';

		state.params = {};
	};

	//打开搜索方案弹出
	const showPlanModal = () => {
		searchbar.value.showPlanModal();
		companyLink();
	};

	//搜索表单提交
	const submitForm = async (formEl: FormInstance | undefined) => {

		search_val.value = "";
		let postParams = {
			begin_date: rangeTime.value[0],
			end_date: rangeTime.value[1],
			employee_name: searchform.employee_name.value,
			job_number: searchform.job_number.value,
			type: searchform.type.value
		};
		state.params = postParams;

		searchbar.value.clear();
		searchbar.value.modalHide();
	};





</script>

<style scoped lang="scss">

:deep(.merak_modal.xq .el-form .el-form-item__label){
	justify-content:flex-end;
}
	.translation {
		/* display: flex;
			flex-direction: column;
			width: 100%;*/
		height: 100%;


	}

	.translation_card {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;

		.table_main {
			/* display: flex;
				flex-direction: column;
				width: 100%;
				height: 100%; */
			flex: auto;
			min-height: 0;
		}
	}

	.translationPad {
		padding: 15px;
	}

	.dian {
		display: inline-block;
		width: 4px;
		height: 4px;
		border-radius: 50px;
		background-color: #fff;
		margin-right: 6px;
		position: relative;
		top: -2px;
	}

	.xq .el-form-item__content {
		color: #303133;
		font-size: 13px;
	}

	:deep(.el-form-item__label) {
		padding-right: 40px;
	}
</style>